package com.itheima.web.controller;

import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.bean.BeanUtil;
import com.itheima.domain.db.Admin;
import com.itheima.util.JwtUtil;
import com.itheima.vo.PageBeanVo;
import com.itheima.web.interceptor.AdminHolder;
import com.itheima.web.manager.AdminManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
public class AdminController {

    @Autowired
    private AdminManager adminManager;
    //生成验证码
    @GetMapping("/system/users/verification")
    public void genVerification(String uuid, HttpServletResponse response) throws IOException {

        //调用manager生成验证码
        LineCaptcha lineCaptcha = adminManager.genVerification(uuid);

        //返回验证码
        response.setContentType("image/jpeg");//声明返回数据的Content-Type
        lineCaptcha.write(response.getOutputStream());
    }



    //用户登录
    @PostMapping("/system/users/login")
    public Map<String, String> login(@RequestBody Map<String, String> map) {

        //接收参数
        String username = map.get("username");
        String password = map.get("password");
        String verificationCode = map.get("verificationCode");
        String uuid = map.get("uuid");

        //调用manager进行登录验证
        String token = adminManager.login(username, password, verificationCode, uuid);

        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);

        //返回给前端
        return tokenMap;
    }


    //基本信息查询
    @PostMapping("/system/users/profile")
    public Map<String, String> findUserInfo() {

        String username = AdminHolder.getAdmin().getUsername();

        Admin admin = adminManager.findUserInfo(username);

        Map<String, String> map = new HashMap<>();
        //BeanUtil.beanToMap(admin, map, true, true);
        map.put("uid", admin.getId()+"");
        map.put("username", admin.getUsername());
        map.put("avatar", admin.getAvatar());

        return map;
    }


    //用户登出
    @PostMapping("/system/users/logout")
    public void logOut(@RequestHeader("Authorization") String token) {

        token = token.replaceAll("Bearer ", "");

        adminManager.logOut(token);

    }

}
